import { EditOutlined } from '@ant-design/icons';
import { Select } from 'antd';
import { isEmpty } from 'lodash-es';
import React, { useEffect, useRef, useState } from 'react';
import { YmDialog } from 'ym-design';
import OStyle from './index.less';
import { PositionInfoProps, positionInfoValue } from './interface';

const PositionInfo: React.FC<PositionInfoProps> = (props) => {
  const { value, onChange } = props;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const mapInstanceRef = useRef<any>();
  const circleRef = useRef<any>();
  const mapContainerRef = useRef<any>(null);
  const searchMapRef = useRef<any>(null);
  const [mapLocation, setMapLocation] = useState<positionInfoValue>(value!);
  const [mapScope, setMapScope] = useState<number>(value?.scope || 100);

  //确认
  const handleOk = () => {
    setIsModalOpen(false);
    //---
    onChange?.({ ...mapLocation, scope: mapScope });
  };
  //取消
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //   useRef().current的值发生变更不会触发re-render，当然也就“监听不到变化”了
  useEffect(() => {
    if (isModalOpen) {
      // console.log('--mapContainerRef.current--外--:', mapContainerRef.current);
      // console.log('--searchMapRef.current--外--:', searchMapRef.current);
      setTimeout(() => {
        if (!mapContainerRef.current || !searchMapRef.current) return;
        // console.log('--mapContainerRef.current--里--:', mapContainerRef.current);
        // console.log('--searchMapRef.current-里--:', searchMapRef.current);
        if (!mapInstanceRef.current) {
          mapInstanceRef.current = new window.AMap.Map(mapContainerRef.current, {
            zoom: 15,
            center: value?.longitude ? [value.longitude, value.latitude] : '', //中心点坐标 // 没有拿到的话，默认空
          });
        }
        // 地图图块加载完成后触发
        mapInstanceRef.current.on('complete', () => {
          console.log('--地图加载完成--');
          //范围
          const circle = new window.AMap.Circle({
            center: mapInstanceRef.current.getCenter(),
            radius: value?.scope, //半径
            borderWeight: 3,
            strokeColor: '#6c97ef',
            strokeOpacity: 1,
            strokeWeight: 6,
            fillOpacity: 0.4,
            fillColor: '#1791fc',
            zIndex: 50,
          });
          mapInstanceRef.current.add([circle]);
          circleRef.current = circle;

          const marker = new window.AMap.Marker();
          // eslint-disable-next-line no-undef
          window.AMapUI.setDomLibrary($); //为了防止 jquery $ is not a function 命名冲突
          window.AMapUI.load(['lib/$'], function ($: any) {
            window.AMapUI.loadUI(
              ['misc/PoiPicker', 'misc/PositionPicker'],
              function (PoiPicker: any, PositionPicker: any) {
                const poiPicker = new PoiPicker({
                  //city:'北京',
                  input: searchMapRef.current, //'pickerInput',
                });
                // window.poiPicker = poiPicker;

                //选取了某个POI
                //POI选点 api文档https://developer.amap.com/api/amap-ui/reference-amap-ui/other/poipicker
                poiPicker.on('poiPicked', function (poiResult: any) {
                  const source = poiResult.source,
                    poi = poiResult.item,
                    info = {
                      source: source,
                      id: poi.id,
                      name: poi.name,
                      location: poi.location.toString(),
                      address: poi.address,
                    };

                  marker.setMap(mapInstanceRef.current);

                  marker.setPosition(poi.location);

                  mapInstanceRef.current.setCenter(marker.getPosition());
                });

                //拖拽选址 api文档https://developer.amap.com/api/amap-ui/reference-amap-ui/other/positionpicker
                const positionPicker = new PositionPicker({
                  mode: 'dragMap',
                  map: mapInstanceRef.current,
                });
                positionPicker.on('success', function (positionResult: any) {
                  console.log('移动地图', positionResult);
                  const { position, address, nearestPOI } = positionResult;
                  circle.setCenter(positionResult.position);

                  // 只要有setState, Map就会实例化多次 Map就会报错 ,所以要用mapInstanceRef.current判断
                  setMapLocation({
                    ...mapLocation,
                    longitude: position.lng,
                    latitude: position.lat,
                    addressName: address,
                    name: nearestPOI,
                  });
                });
                positionPicker.start();
              },
            );
          });
        });
      }, 500);
    }
    return () => {
      // 会报错
      if (mapInstanceRef.current) {
        console.log('---地图销毁---');
        mapInstanceRef.current.destroy();
        mapInstanceRef.current = null;
      }
    };
  }, [isModalOpen]);

  return (
    <>
      {!isEmpty(value) && (
        <p>
          <span>{value?.name}</span>&nbsp;<span>半径：{value.scope}</span>&nbsp;
          <EditOutlined
            style={{ color: 'rgb(255, 109, 59)' }}
            onClick={() => {
              setIsModalOpen(true);
            }}
          />
        </p>
      )}

      <YmDialog
        title="学习点设置"
        centered
        width={1120}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        onClose={handleCancel}
        destroyOnClose={true} //  map 报错： div container do not exit, 但是加了setTimeout(() => {},1000) 之后就好了？？？mapContainerRef.current还没加载完？？？
      >
        <div className={OStyle.map_top_box}>
          <div className={OStyle.box_item}>
            <label htmlFor="searchMap">位置搜索：</label>
            <input
              ref={searchMapRef}
              style={{
                width: '300px',
                height: '30px',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                padding: '0 11px',
              }}
              placeholder="可通过移动地图或搜索获取精准位置"
              id="pickerInput"
            />
          </div>
          <div className={`${OStyle.box_item} ${OStyle.box_item_position_name}`}>
            <p className={OStyle.name_label}>打卡点：</p>
            <div className={OStyle.name_text}>
              <p>{mapLocation?.name}</p>
              <p style={{ color: '#999' }}>{mapLocation?.addressName}</p>
            </div>
          </div>
          <div className={OStyle.box_item}>
            <span>打卡范围：</span>
            <Select
              value={mapScope}
              options={[
                { label: '半径50米', value: 50 },
                { label: '半径100米', value: 100 },
                { label: '半径200米', value: 200 },
                { label: '半径300米', value: 300 },
                { label: '半径400米', value: 400 },
                { label: '半径500米', value: 500 },
              ]}
              onChange={(val) => {
                circleRef.current?.setRadius(val);
                mapInstanceRef.current?.setFitView([circleRef.current]);
                // onChange?.({ ...value, scope: val });
                // 也会触发positionPicker.on('success'）
                setMapScope(val);
              }}
            ></Select>
          </div>
        </div>

        {/*地图*/}
        <div ref={mapContainerRef} id="mapContainer" style={{ width: '100%', height: '300px' }}></div>
      </YmDialog>
    </>
  );
};

export default PositionInfo;
